import Vue from 'vue'
import Vuex from 'vuex'
import { loginReq, getInfoReq } from '@/api/user'
import Cookies from 'js-cookie'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user_id: null,
    user_name: '',
    email: '',
  },
  mutations: {
    // 设置存储在store里的用户信息
    setUserInfoMutations(state, info) {
      const { user_name, email, logout } = info
      state.user_name = user_name
      state.email = email
      if (logout) {
        Cookies.set('token', '')
      }
    },
  },
  actions: {
    loginActions({ commit, dispatch }, { user_name, password }) {
      return new Promise((resolve, reject) => {
        loginReq({ user_name, password }).then(response => {
          const {
            data: { code, msg, data },
          } = response
          if (code === 0) {
            Cookies.set('token', 'value')
            dispatch('getInfoActions').then(resp => {
            console.log("TCL: loginActions -> resp", resp)
              resolve(resp)
            })
          } else {
            console.error(msg)
          }
        })
      })
    },
    getInfoActions({ commit }) {
      return new Promise((resolve, reject) => {
        getInfoReq().then(resp => {
          const {
            data: { code, data },
          } = resp
          if (code === 0) {
            commit('setUserInfoMutations', data)
            resolve(resp)
          }
        })
      })
    },
  },
})
